/** 
  考核指标设置
*/
<template>
  <div>
    <el-card shadow="never" body-style="padding: 24px;" class="condition-card">
      <el-form label-position="right" label-suffix="：" label-width="150px">
        <el-row :gutter="24" style="height: 50px;">
          <el-col :span="3" style="line-height: 33px;">
            <span class="condition-title">{{ $t("message.filterCondition") }}</span>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('templateSetting.templateName')">
              <el-input disabled v-model="currentTemplateInfo.templateName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('asesmentSetting.assessmentIndexName')">
              <el-input disabled v-model="currentAssessIndex.itemName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
      <h1 class="condition-title">{{ $t('asesmentSetting.assessDetailsSetTable') }}</h1>
      <div class="edu-opertion-bar sub-title">
        <div class="float-right" style="display: flex;">
          <el-button v-if="permitToEdit" @click="editAssessIndex">{{ $t('common.btn.edit') }}</el-button>
          <el-button v-if="permitToSave && editModel" @click="saveAssessIndex">{{$t('common.btn.save')}}</el-button>
          <el-button v-if="permitToAddRow && editModel" type="primary" @click="addLine">{{$t('graduateBase.addLine')}}</el-button>
          <el-button v-if="permitToDeleteRow && editModel" type="danger" @click="delLine">{{$t('graduateBase.deleteLine')}}</el-button>
        </div>
      </div>
      <el-form :model="assessIndexDetailTable" ref="assessIndexDetailTable" :rules="rulesForm">
        <edu-table :pagination="false" :order='false' :tooltipEffect="tooltipEffect" stripe :data="assessIndexDetailTable.dataList" size="mini" @selection-change="handleSelectionChange">
          <edu-table-column :label="$t('asesmentSetting.assessmentDetails')" prop="detailName">
            <template slot-scope="scope">
              <el-form-item v-if="editModel" style="margin-top: 15px;" :prop="'dataList.' + scope.$index + '.detailName'" label-width="0" :rules="rulesForm.detailName">
                <el-input v-model.trim="scope.row.detailName" :maxlength="64" clearable></el-input>
              </el-form-item>
              <div v-else>{{ scope.row.detailName }}</div>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('asesmentSetting.assessmentDetailsDesc')" prop="description">
            <template slot-scope="scope">
              <el-form-item v-if="editModel" style="margin-top: 15px;" :prop="'dataList.' + scope.$index + '.description'" label-width="0" :rules="rulesForm.description">
                <el-input v-model.trim="scope.row.description" :maxlength="512" clearable></el-input>
              </el-form-item>
              <div v-else>{{ scope.row.description }}</div>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('asesmentSetting.assessmentDetailsWeig')" prop="weight">
            <template slot-scope="scope">
              <el-form-item v-if="editModel" style="margin-top: 15px;" :prop="'dataList.' + scope.$index + '.weight'" label-width="0" :rules="rulesForm.weight">
                <el-input v-model.trim="scope.row.weight" clearable></el-input>
              </el-form-item>
              <div v-else>{{ scope.row.weight }}</div>
            </template>
          </edu-table-column>
        </edu-table>
      </el-form>
      <!-- <el-row type="flex" class="row-bg" justify="end">
        <el-col>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryForm.pageNum_"
            :page-sizes="[20, 40, 80, 100]"
            :page-size="queryForm.pageSize_"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryForm.total_"
            style="float:right;margin-top:10px"
          ></el-pagination>
        </el-col>
      </el-row> -->
    </el-card>
  </div>
</template>
<script>
import graduateStudentApi from 'common/src/api/graduateStudent/graduateStudent';
export default {
  components: {
  },
  data () {
    return {
      auths: [],
      permitToEdit: false,
      permitToSave: false,
      permitToAddRow: false,
      permitToDeleteRow: false,
      currentTemplateInfo: '',
      deleteInfo: [],
      queryForm: {
        pageNum_: 1,
        pageSize_: 99999,
        total_: 0,
        condition: {
          itemId: ''
        }
      },
      assessIndexDetailTable: {
        dataList: []
      },
      editModel: false,
      indexKey: '1', // 面包屑
      title: '',
      multipleSelection: [],
      options: {
        templateId: []
      },
      rulesForm: {
        detailName: [
          { required: true, message: this.$t('asesmentSetting.requireAssessIndexDetail'), trigger: 'blur' },
          { validator: this.checkSpecial, trigger: 'blur'}
        ],
        description: [
          { required: true, message: this.$t('asesmentSetting.requireAssessIndexDesDetail'), trigger: 'blur' },
          { validator: this.checkSpecial, trigger: 'blur'}
        ],
        weight: [
          {
            validator: this.validateWeight,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  props: {
    currentTemplate: {
      type: Object,
      default: () => {}
    },
    currentAssessIndex: {
      type: Object,
      default: () => {}
    }
  },
  created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths;
      }
    }
  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im;
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback();
      }
    },
    // 校验考核指标权重
    validateWeight(rule, value, callback) {
      let expReg = /^(\d{1})(\.\d{1,2})?$/;
      if (!value) {
        callback(new Error(this.$t('asesmentSetting.requireAssessIndexWeigDetail')));
      } else if (!expReg.test(value)) {
        callback(new Error(this.$t('asesmentSetting.validateAssessIndexWeig')))
      } else if (Number(value) === 0 || Number(value) > 1) {
        callback(new Error(this.$t('asesmentSetting.validateAssessIndexWeig')));
      } else {
        callback();
      }
    },
    // 编辑
    editAssessIndex() {
      this.editModel = !this.editModel;
      this.onSubmit();
    },
    // 保存考核指标设置
    saveAssessIndex() {
      this.$refs['assessIndexDetailTable'].validate((valid) => {
        if (valid) {
          this.assessIndexDetailTable.dataList.map((item) => {
            item['itemId'] = this.currentAssessIndex.id;
            item['deleteFlag'] = '0';
          });
          let currentDeleteInfo = JSON.parse(JSON.stringify(this.deleteInfo));
          if (currentDeleteInfo.length > 0) {
            currentDeleteInfo.map(item => {
              item['itemCategory'] = '1';
              item['deleteFlag'] = '1';
            });
          }
          graduateStudentApi.saveAssessDetails({
            "templateId": this.currentTemplateInfo.id,
            "itemId": this.currentAssessIndex.id,
            "itemCategory": '1',
            "detailList": this.assessIndexDetailTable.dataList.concat(currentDeleteInfo)
          }).then(res => {
            if (res.code === 200) {
              this.$message.success(this.$t('graduateBase.savedSuccessfully'));
              this.editModel = false;
              this.onSubmit();
            }
          });
        } else {
          setTimeout(() => {
            let isError = document.getElementsByClassName("is-error");
            if (isError[0] && isError[0] && isError[0].querySelector('input')) {
              isError[0].querySelector('input').focus();
            }
          }, 1);
        }
      });
    },
    // 新增行
    addLine() {
      this.assessIndexDetailTable.dataList.push({
        "uniqueId": new Date().getTime(),
        "itemId": this.currentAssessIndex.id,
        "detailName": "",
        "description": "",
        "weight": "",
        "deleteFlag": "0"
      });
    },
    // 删除行
    delLine() {
      let _this = this;
      if (this.multipleSelection.length > 0) {
        this.$delConfirm().then(_ => {
          this.deleteInfo = this.multipleSelection;
          for (let i = _this.assessIndexDetailTable.dataList.length - 1; i >= 0; i--) {
            _this.multipleSelection.map((element) => {
              if (_this.assessIndexDetailTable.dataList[i]) {
                if ((_this.assessIndexDetailTable.dataList[i].id && _this.assessIndexDetailTable.dataList[i].id === element.id) || (_this.assessIndexDetailTable.dataList[i].uniqueId && _this.assessIndexDetailTable.dataList[i].uniqueId === element.uniqueId)) {
                  _this.assessIndexDetailTable.dataList.splice(i, 1);
                }
              }
            });
          }
          this.$message(this.$t('graduateBase.shouldSave'));
        }).catch(_ => {
        });
      } else {
        this.$message(this.$t('graduateBase.pleaseChoose'));
      }
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1;
      this.getListData();
    },
    getListData() {
      this.deleteInfo = [];
      graduateStudentApi.assessDetailsList({
        "pageNum_": this.queryForm.pageNum_,
        "pageSize_": this.queryForm.pageSize_,
        "condition": {
          "itemId": this.queryForm.condition.itemId,
        }
      }).then((res) => {
        this.assessIndexDetailTable.dataList = res.data.list;
        this.queryForm.total_ = res.data.total_;
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val;
      this.getListData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val;
      this.getListData();
    }
  },
  watch: {
    currentTemplate: {
      handler(newVal) {
        if (newVal) {
          this.currentTemplateInfo = newVal;
        }
      },
      deep: true,
      immediate: true
    },
    currentAssessIndex: {
      handler(newVal) {
        if(newVal) {
          this.queryForm.condition.itemId = newVal.id;
          graduateStudentApi.assessDetailsList(this.queryForm).then(res => {
            if (res.code === 200) {
              this.assessIndexDetailTable.dataList = res.data.list;
              this.queryForm.total_ = res.data.total_;
            }
          });
        } 
      },
      deep: true,
      immediate: true
    },
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            if (item.authCode === 'graduateStu-assessIndexDetail-edit') {
              this.permitToEdit = true;
            }
            if (item.authCode === 'graduateStu-assessIndexDetail-save') {
              this.permitToSave = true;
            }
            if (item.authCode === 'graguateStu-assessIndexDetail-addRow') {
              this.permitToAddRow = true;
            }
            if (item.authCode === 'graduateStu-assessIndexDetail-deleteRow') {
              this.permitToDeleteRow = true;
            }
          });
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
  .condition-card ::v-deep {
    .el-row {
      height: 30px!important;
    }
    .el-form-item {
      margin-bottom: 0!important;
    }
  }
  .condition-title {
    color: #2b3b4e;
    font-size: 18px;
    line-height: 24px;
    font-weight: bold;
  }
  .sub-title {
    margin: 16px 0;
    font-size: 16px;
    color: #000020;
    letter-spacing: 0;
  }
</style>
